package com.qiaoba.web.config;

import cn.hutool.core.io.IoUtil;
import com.qiaoba.web.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.InputStream;

/**
 * 离线IP设置
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/25 16:32
 */
@Slf4j
@Component
public class IpConfig {

    @PostConstruct
    public void dbToCache() {
        InputStream inputStream = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource("ip2region.xdb");
            inputStream = classPathResource.getInputStream();
            IpUtil.setSearcher(Searcher.newWithBuffer(IoUtil.read(inputStream).toByteArray()));
            log.info("加载IP离线库到内存成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("加载IP离线库到内存失败, 请联系管理员！");
        } finally {
            IoUtil.close(inputStream);
        }
    }

    @PreDestroy
    public void close() {
        IpUtil.closeSearcher();
        log.info("IP离线库已关闭");
    }
}
